package com.mx.controller;

import com.mx.pojo.Article;
import com.mx.pojo.ArticleTag;
import com.mx.pojo.Tag;
import com.mx.service.ArticleService;
import com.mx.service.ArticleTagService;
import com.mx.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    ArticleService articleService;

    @Autowired
    TagService tagService;

    @Autowired
    ArticleTagService articleTagService;

    @RequestMapping({"/blog"})
    public String blog(Model model){
        List<Article> articles = articleService.findAll();
        Collections.reverse(articles);
        model.addAttribute("articles",articles);
        return "admin/dashboard";
    }

    @RequestMapping("/toAddArticle")
    public String toAddArticle(Article article,Model model){
        List<Tag> tags = tagService.findAll();
        model.addAttribute("tags",tags);
        return "admin/toAddArticle";
    }


    @RequestMapping("/deleteArticle")
    public String deleteArticle(Integer id,Model model){
        articleTagService.delete(id);
        articleService.delete(id);
        return "redirect:/admin/blog";
    }

    @RequestMapping("/toUpdateArticle")
    public String toUpdateArticle(Integer id,Model model){
        Article oldArticle = articleService.findId(id);
        model.addAttribute("oldArticle",oldArticle);

        //找到改文章有的所有标签
        List<ArticleTag> temp = articleTagService.findAid(oldArticle.getId());
        ArrayList<Integer> oldTags = new ArrayList<>();
        for (ArticleTag articleTag : temp) {
            oldTags.add(articleTag.getTid());
        }
        model.addAttribute("oldTags",oldTags);

        List<Tag> tags = tagService.findAll();
        model.addAttribute("tags",tags);
        return "admin/toUpdateArticle";
    }

    @RequestMapping("/updateArticle")
    public String updateArticle(Article article,Integer tags[],@RequestParam("file") MultipartFile pic){
        if(pic.isEmpty()){
            System.err.println("上传的图片为空");
            article.setImage(articleService.findId(article.getId()).getImage());
        }else{
            // ResourceUtils.getURL("classpath:") 是获取当前文件的resources路径
            try {
                // 获取文件的原始名称
                String oldFileName = pic.getOriginalFilename();
                String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
                // 处理文件上传
                realPath=realPath.substring(1);
                File file = new File(realPath);
                if(!file.exists())
                    file.mkdir();
                System.out.println(realPath);
                pic.transferTo(new File(realPath,oldFileName));
                article.setImage("/files/"+oldFileName);
                System.out.println("downloadPath:/files/"+oldFileName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        article.setDate(new Date());

        System.out.println(Arrays.toString(tags));
        System.out.println(article);

        articleService.update(article);

        articleTagService.delete(article.getId());

        for (Integer tag : tags) {
            articleTagService.save(new ArticleTag(null,article.getId(),tag));
        }

        return "redirect:/admin/blog";
    }

    @RequestMapping("/addArticle")
    public String addArticle(Integer tags[],Article article,@RequestParam("file") MultipartFile pic){
        String downloadPath="";
        if(pic.isEmpty()){
            System.err.println("上传的图片为空");
        }
        else{
            // ResourceUtils.getURL("classpath:") 是获取当前文件的resources路径
            try {
                // 获取文件的原始名称
                String oldFileName = pic.getOriginalFilename();
                String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
                // 处理文件上传
                realPath=realPath.substring(1);
                File file = new File(realPath);
                if(!file.exists())
                    file.mkdir();
                System.out.println(realPath);
                pic.transferTo(new File(realPath,oldFileName));
                downloadPath="/files/"+oldFileName;
                System.out.println("downloadPath:/files/"+oldFileName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        article.setDate(new Date());
        article.setImage(downloadPath);

        System.out.println(Arrays.toString(tags));
        System.out.println(article);

        articleService.save(article);
        List<Article> all = articleService.findAll();
        Article temp = all.get(all.size() - 1);

        if(tags!=null)
        {
            for (Integer tag : tags) {
                articleTagService.save(new ArticleTag(null,temp.getId(),tag));
            }
        }


        return "redirect:/admin/blog";
    }

    @RequestMapping("/tag")
    public String tag(Model model){
        List<Tag> tags = tagService.findAll();
        model.addAttribute("tags",tags);
        return "admin/tagManage";
    }

    @RequestMapping("/addTag")
    public String toAddTag(Tag tag){
        tagService.save(tag);
        System.out.println("tag:"+tag);
        return "redirect:/admin/tag";
    }

    @RequestMapping("/deleteTag")
    public String deleteTag(Integer id){
        tagService.delete(id);
        return "redirect:/admin/tag";
    }



    @RequestMapping("/upload")
    @ResponseBody
    public HashMap<String, Object> upload(@RequestParam("editormd-image-file") MultipartFile pic,Model model){
        System.out.println("进入upload方法");
        String downloadPath="";
        if(pic.isEmpty()){
            System.err.println("上传的图片为空");
        }
        else{
            // ResourceUtils.getURL("classpath:") 是获取当前文件的resources路径
            try {
                // 获取文件的原始名称
                String oldFileName = pic.getOriginalFilename();
                String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
                // 处理文件上传
                realPath=realPath.substring(1);
                File file = new File(realPath);
                if(!file.exists())
                    file.mkdir();
                System.out.println(realPath);
                pic.transferTo(new File(realPath,oldFileName));
                downloadPath="http://localhost:8084/files/"+oldFileName;
                System.out.println("downloadPath:http://localhost:8084/files/"+oldFileName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("url",downloadPath);
        map.put("success", 1);
        map.put("message", "upload success!");

        return map;
    }

}
